import React, { useState, useCallback, useMemo } from 'react';
import './style.scss';
import { useEffect } from 'react';

const Slider = ({
    title,
    value = 50,
    min = 0,
    max = 100,
    onChange,
    style,
    disabled,
}) => {
    const [rendvalue, setRendValue] = useState(value);

    const handleChange = useCallback(
        (e) => {
            // 如果被禁用，则不处理变化
            if (disabled) return;

            console.log('slider');
            const newValue = Math.round(parseInt(e.target.value, 10));
            setRendValue(newValue);
            onChange && onChange(newValue);
        },
        [onChange, disabled]
    );

    useEffect(() => {
        setRendValue(Math.round(parseInt(value, 10)));
    }, [value]);

    // 计算百分比，使用 useMemo 确保值变化时会重新计算
    const percentage = useMemo(() => {
        return ((rendvalue - min) / (max - min)) * 100;
    }, [rendvalue, min, max]);

    return (
        <div className="slider-container" style={style}>
            <div className="slider-header">
                <span className="slider-title">{title}</span>
                <span className="slider-value">{rendvalue}%</span>
            </div>

            <div className="slider-wrapper">
                <input
                    type="range"
                    min={min}
                    max={max}
                    value={rendvalue}
                    onChange={handleChange}
                    disabled={disabled} // 添加禁用属性
                    className="slider"
                    style={{
                        background: `linear-gradient(to right, #3F00FF 0%, #3F00FF ${percentage}%, #4A4A5B ${percentage}%, #4A4A5B 100%)`,
                        // 可以添加额外的样式来表示禁用状态
                        opacity: disabled ? 0.5 : 1,
                        cursor: disabled ? 'not-allowed' : 'pointer',
                    }}
                />
            </div>
        </div>
    );
};

export default Slider;
